1631D - Range and Partition - CodeForces Solution


binary search constructive algorithms greedy two pointers *1800

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"

void solve(){
    int n,k;
    cin>>n>>k;
    vector<int> v(n);
    for(auto &i:v) cin>>i;
    int req = (n+k+1)/2;
    auto vv = v;
    sort(vv.begin(),vv.end());
    vector<int> ans = {n+1,-1,-1};
    for(int i=0;i<n-req+1;i++){
        int d = vv[i+req-1] - vv[i];
        ans = min(ans,{d,vv[i],vv[i+req-1]});
    }
    int x = ans[1],y = ans[2];
    int sum = 0,cnt = 0,prev = 1;
    cout<<x<<" "<<y<<endl;
    for(int i=0;i<n;i++){
        if(v[i] >= x && v[i]<= y) sum++;
        else sum--;
        if(sum > 0 && cnt < k-1){
            cout<<prev<<" "<<i+1<<endl;
            prev = i+2;
            sum = 0;
            cnt++;
        }
    }
    cout<<prev<<" "<<n<<endl;
}
signed main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    int t;
    cin>>t;
    while(t--){
        solve();
    }
    // for(int i=12;i<=12;i++){
    //     int n = (1<<i);
    //     for(int k = 0;k<n-1;k++){
    //         auto res = solve(n,k);
    //         int x = 0;
    //         for(auto &p:res) x = x + (p.first & p.second);
    //         if(x != k) cout<<n<<" "<<k<<" "<<x<<endl;
    //     }
    // }
}


Comments

Submit
0 Comments
More Questions

236A - Boy or Girl
271A - Beautiful Year
520B - Two Buttons
231A - Team
479C - Exams
1030A - In Search of an Easy Problem
158A - Next Round
71A - Way Too Long Words
160A - Twins
1A - Theatre Square
1614B - Divan and a New Project
791A - Bear and Big Brother
1452A - Robot Program
344A - Magnets
96A - Football
702B - Powers of Two
1036A - Function Height
443A - Anton and Letters
1478B - Nezzar and Lucky Number
228A - Is your horseshoe on the other hoof
122A - Lucky Division
1611C - Polycarp Recovers the Permutation
432A - Choosing Teams
758A - Holiday Of Equality
1650C - Weight of the System of Nested Segments
1097A - Gennady and a Card Game
248A - Cupboards
1641A - Great Sequence
1537A - Arithmetic Array
1370A - Maximum GCD